package com.ppxkk.city;

import android.annotation.SuppressLint;
import android.app.*;
import android.os.*;
import android.content.*;
import android.widget.*;
import android.content.SharedPreferences.*;
import org.json.*;
import java.net.*;
import java.io.*;
import java.security.*;
import android.widget.*;
import android.view.*;
import android.animation.*;

public class OneActivity extends Activity
{
    private LinearLayout hasAccountLayout;
    private TextView UserName,attribute,userInfo;
    private Button LoginBtn,LoginOnlyBtn;
    private SharedPreferences sp;
    private String key = "49ff2878167a5979";
    //后台Key值
    private String token = "1158e285f1cd9871b094fd1f056bb96f";
    private HttpURLConnection h;

    @SuppressLint("WrongConstant")
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one);
        //init views
        attribute=findViewById(R.id.attribute);
        UserName = findViewById(R.id.userName);
        LoginBtn = findViewById(R.id.loginButton);
        LoginOnlyBtn = findViewById(R.id.loginOnlyButton);
        hasAccountLayout = findViewById(R.id.hasAccount);
        userInfo=findViewById(R.id.info);
        ((LinearLayout)findViewById(R.id.mainLinearLayout)).setLayoutTransition(new LayoutTransition());
        //account storage
        sp = getSharedPreferences("user", MODE_PRIVATE);
        String user=sp.getString("user", "");
        findViewById(R.id.passwordButton).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(final View p1){
                Intent i= new Intent();
                i.setClassName(OneActivity.this, "com.ppxkk.city.ChangePasswordActivity");
                startActivity(i);
            }
        });
        findViewById(R.id.attributeButton).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(final View p1){
                Intent i= new Intent();
                i.putExtra("attr",attribute.getText());
                i.setClassName(OneActivity.this, "com.ppxkk.city.ChangeAttributeActivity");
                startActivityForResult(i,3);
            }
        });
        findViewById(R.id.checkInButton).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(final View p1)
            {
                final String n=sp.getString("user", "");
                final String p=sp.getString("password", "");
                if (h != null)
                {
                    //cancel previous
                    h.disconnect();
                    h = null;
                }
                Toast.makeText(OneActivity.this, "正在签到", Toast.LENGTH_LONG).show();
                //MD5加密Token -> （key+user+pass+后台token值）
                //Toast.makeText(OneActivity.this, 接口 + "&key=" + key + "&token=" + token + "&user=" + n + "&pass=" + p, Toast.LENGTH_LONG).show();
                new Thread(new HttpRunnable(
                        "http://i.agyer.com/user_info.json?type=qd",
                        key,
                        n,
                        p,
                        hash((key + n + p + token).getBytes()),
                        new HttpReceiveCallback(){
                            @Override
                            public void onReceive(Message msg)
                            {
                                //获取更新来的内容
                                Bundle data=msg.getData();
                                String message;
                                int result=0;
                                String jsonString=data.getString("message", "{}");
                                try
                                {
                                    //解析js
                                    JSONObject js=new JSONObject(jsonString);
                                    result = js.getInt("code");
                                    //获取message的信息
                                   // message = js.getString("message");
                                    message = "已签到";
                                }
                                catch (JSONException e)
                                {
                                    e.printStackTrace();
                                    message = "签到失败";
                                }
                                Toast.makeText(OneActivity.this, message, Toast.LENGTH_LONG).show();
                                if(message.equals("今日已签到")||result==1){
                                    ((TextView)p1).setText("已签到");
                                }else{
                                    ((TextView)p1).setText("签到");
                                }
                                if (result==1){
                                    login(n, p,false);
                                }
                            }
                        }
                )).start();
            }
        });
        LoginBtn.setOnClickListener(new View.OnClickListener(){
            @SuppressLint("WrongConstant")
            @Override
            public void onClick(View p1)
            {
                // Toast.makeText(OneActivity.this, (h != null ?h.toString(): "") + sp.getString("user", ""), Toast.LENGTH_LONG).show();
                if (h != null)
                {
                    Toast.makeText(OneActivity.this, "仍在登录，请稍后", Toast.LENGTH_LONG).show();
                    return;
                }
                else if (sp.getString("user", "") != "")
                {
                    //log out
                    SharedPreferences.Editor e=sp.edit();
                    e.remove("user");
                    e.remove("password");
                    e.apply();
                    UserName.setText("未登录");
                    LoginBtn.setText("注册");
                    LoginOnlyBtn.setVisibility(0);
                    Toast.makeText(OneActivity.this, "已登出", Toast.LENGTH_LONG).show();
                    hasAccountLayout.setVisibility(8);
                    return;
                }
                //go to login
                Intent i= new Intent();
                i.setClassName(OneActivity.this, "com.ppxkk.city.RegisterActivity");
                startActivityForResult(i, 1);
            }
        });
        LoginOnlyBtn.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View p1)
            {
                Intent i= new Intent();
                i.setClassName(OneActivity.this, "com.ppxkk.city.LoginActivity");
                startActivityForResult(i, 2);
            }


        });
        //has logged in?
        if (user == "")
        {
            //not yet logged in
            Toast.makeText(OneActivity.this, "请先登录", Toast.LENGTH_LONG).show();
            /*Intent i= new Intent();
             i.setClassName(OneActivity.this, "com.ppxkk.city.RegisterActivity");
             startActivityForResult(i, 1);*/
            UserName.setText("未登录");
            LoginBtn.setText("注册");
            LoginOnlyBtn.setVisibility(0);
            hasAccountLayout.setVisibility(8);
        }
        else
        {
            //log in already
            //do login api
            login(user,
                    sp.getString("password", "")
            );
            UserName.setText("登录");
            LoginBtn.setText("登录");
            LoginOnlyBtn.setVisibility(8);
            hasAccountLayout.setVisibility(0);
        }
    }

    @SuppressLint("WrongConstant")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==3){
            if (data == null)
            {
                //attribute edit cancel
                Toast.makeText(OneActivity.this, "未修改自定义参数", Toast.LENGTH_LONG).show();
                return;
            }
            attribute.setText(data.getStringExtra("attr"));
        }
        else if (requestCode == 2)
        {
            if (data == null)
            {
                //login cancel
                Toast.makeText(OneActivity.this, "登录已取消", Toast.LENGTH_LONG).show();
                return;
            }
            //store account
            String u=data.getStringExtra("user");
            String p=data.getStringExtra("password");
            SharedPreferences.Editor e=sp.edit();
            e.putString("user", u);
            e.putString("password", p);
            e.apply();
            //do login api
            //login(u, p);
            UserName.setText("欢迎  " + u+"  回来！");
            LoginBtn.setText("注销");
            LoginOnlyBtn.setVisibility(8);
            //Toast.makeText(OneActivity.this, "regist successful,login automatically", Toast.LENGTH_LONG).show();
            hasAccountLayout.setVisibility(0);
        }
        else if (requestCode == 1)
        {
            if (data == null)
            {
                //login cancel
                Toast.makeText(OneActivity.this, "注册已取消", Toast.LENGTH_LONG).show();
                return;
            }
            //store account
            String u=data.getStringExtra("user");
            String p=data.getStringExtra("password");
            SharedPreferences.Editor e=sp.edit();
            e.putString("user", u);
            e.putString("password", p);
            e.apply();
            //do login api
            login(u, p);
            //Toast.makeText(OneActivity.this, "regist successful,login automatically", Toast.LENGTH_LONG).show();
        }
    }

    private void login(String n, String p){
        login(n,p,true);
    }

    private void login(String n, String p,final boolean notify)
    {
        if (h != null)
        {
            //cancel previous
            h.disconnect();
            h = null;
        }
        if (notify){
            Toast.makeText(OneActivity.this, "登陆中", Toast.LENGTH_LONG).show();
        }
        //MD5加密Token -> （key+user+pass+后台token值）
        //Toast.makeText(OneActivity.this, 接口 + "&key=" + key + "&token=" + token + "&user=" + n + "&pass=" + p, Toast.LENGTH_LONG).show();
        new Thread(new HttpRunnable(
                "http://i.agyer.com/user_info.json?type=info",
                key,
                n,
                p,
                hash((key + n + p + token).getBytes()),
                new HttpReceiveCallback(){
                    @SuppressLint("WrongConstant")
                    @Override
                    public void onReceive(Message msg)
                    {
                        //获取更新来的内容
                        Bundle data=msg.getData();
                        // String message;
                        int result=0;
                        String attr="";
                        String regTime="",coin="";
                        String jsonString=data.getString("message", "{}");
                        try
                        {
                            //解析js
                            JSONObject js=new JSONObject(jsonString);
                            result = js.getInt("code");
                            //获取message的信息
                            // message = js.getString("message");
                            attr=js.getString("custom");
                            regTime=js.getString("regtime");
                            coin=js.getString("jf");
                        }
                        catch (JSONException e)
                        {
                            e.printStackTrace();
                            //message = "access error";
                        }
                        //Toast.makeText(OneActivity.this, result+message, Toast.LENGTH_LONG).show();
                        if (result == 1)
                        {
                            String user=data.getString("user");
                            if (user == null)
                            {
                                return;
                            }
                            UserName.setText("欢迎  " + user+ "  回来！");
                            LoginBtn.setText("登出");
                            LoginOnlyBtn.setVisibility(8);
                            hasAccountLayout.setVisibility(0);
                            attribute.setText(attr);
                            userInfo.setText("注册时间："+regTime+"\n积分"+coin);
                            if(notify){
                                Toast.makeText(OneActivity.this, "登录成功", Toast.LENGTH_LONG).show();
                            }
                        }
                        else
                        {
                            UserName.setText("登录失败");
                            LoginBtn.setText("注册");
                            //LoginOnlyBtn.setVisibility(8);
                            if (notify){
                                Toast.makeText(OneActivity.this, "登陆失败", Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                }
        )).start();
    }

    abstract private class HttpReceiveCallback
    {
        public abstract void onReceive(Message ms);

    }

    private class HttpRunnable implements Runnable
    {
        private String api;
        private String key;
        private String user;
        private String pass;
        private String token;
        private HttpReceiveCallback cb;

        private Handler hd=new Handler(){

            @Override
            public void handleMessage(Message msg)
            {

                super.handleMessage(msg);
                h = null;
                cb.onReceive(msg);
            }

        };

        public HttpRunnable(String api, String key, String user, String pass, String token, HttpReceiveCallback cb)
        {
            this.api = api;
            this.key = key;
            this.user = user;
            this.pass = pass;
            this.token = token;
            this.cb = cb;
            //  Toast.makeText(OneActivity.this, ""+token.length(), Toast.LENGTH_LONG).show();

        }

        @Override
        public void run()
        {
            try
            {
                h = (HttpURLConnection) new URL(
                        api + "&key=" + key + "&token=" + token + "&user=" + user + "&pass=" + pass
                ).openConnection(Proxy.NO_PROXY);
                h.setRequestMethod("POST");
                /*h.addRequestProperty("key", this.key);
                 h.addRequestProperty("token", this.token);
                 h.addRequestProperty("user", this.user);
                 h.addRequestProperty("pass", this.pass);*/
                h.setUseCaches(true);
                h.setConnectTimeout(3000);
                h.connect();
                //读取流内容
                InputStream i=h.getInputStream();
                InputStreamReader ir=new InputStreamReader(i);
                BufferedReader br=new BufferedReader(ir);
                StringBuilder sb=new StringBuilder();
                String read;
                //循环读取
                while (true)
                {
                    read = br.readLine();
                    //没有了，跳出循环
                    if (read == null)
                    {
                        break;
                    }
                    sb.append(read);
                }
                h.disconnect();
                //通知更新
                Message m=new Message();
                Bundle bundle=new Bundle();
                bundle.putString("message",
                        sb.toString()
                );
                bundle.putString("user", user);
                //bundle.putString("pass", pass);
                m.setData(bundle);
                hd.sendMessage(m);
            }
            catch (Exception e)
            {
                e.printStackTrace();
                //通知更新
                Message m=new Message();
                Bundle bundle=new Bundle();
                bundle.putString("message",
                        e.getMessage()
                );
                m.setData(bundle);
                hd.sendMessage(m);
            }


        }
    }

    private String hash(byte[] btInput)
    {
        char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
        try
        {
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++)
            {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

}
